package com.yuneec.fly.views;

import android.app.Activity;
import android.app.FragmentManager;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.RemoteException;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.CoordinateConverter;
import com.amap.api.maps.MapsInitializer;
import com.amap.api.maps.TextureMapView;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.Circle;
import com.amap.api.maps.model.CircleOptions;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.Polyline;
import com.amap.api.maps.model.PolylineOptions;
import com.yuneec.fly.GlobalParams;
import com.yuneec.fly.R;
import com.yuneec.fly.fragments.MapFragment;
import com.yuneec.fly.utils.BitmapUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by jw.gu on 2016/6/13.
 */
public class AmapView extends AbstractMapView {
    private AMap aMap;
    private TextureMapView mMapView = null;
    private ArrayList<Marker> pointMarkers;
    private ArrayList<Marker> interestMarkers;
    private HashMap<String, Integer> pointIds;
    private HashMap<String, Integer> interestIds;
    private HashMap<String, Circle> circles;
    private MapFragment mapFragment;
    private DrawerView drawerView;
    private Marker longClickMarker;
    private Marker landPointMarker;
    private Marker droneMarker;
    private Marker panMarker;
    private Marker controllerMarker;
    private LatLng droneLocation;
    private LatLng controllerLocation;
    private float droneAngle;
    private int panAngle;
    private Polyline unFliedRoute;
    private Polyline fliedRoute;
    private CoordinateConverter converter;// GPS坐标转换器
    private FragmentManager mFragmentManager;
    private Handler handler = new Handler();
//    private float lastX0,lastY0,lastX1,lastY1;

    public AmapView(Context context, Bundle savedInstanceState, MapFragment mapFragment, final InitCompleteListener listener) {
        super(context);
        this.mapFragment = mapFragment;
        mFragmentManager = ((Activity) context).getFragmentManager();
        pointMarkers = new ArrayList<>();
        interestMarkers = new ArrayList<>();
        pointIds = new HashMap<>();
        interestIds = new HashMap<>();
        circles = new HashMap<>();
        try {
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                MapsInitializer.sdcardDir = new File(Environment.getExternalStorageDirectory(), "map").toString();
            } else {
                MapsInitializer.sdcardDir = new File(Environment.getRootDirectory(), "map").toString();
            }
            MapsInitializer.initialize(context);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        mView = LayoutInflater.from(context).inflate(R.layout.amap_view_layout, this, true);

        mMapView = (TextureMapView) mView.findViewById(R.id.mapView);
        drawerView = (DrawerView) mView.findViewById(R.id.drawerView);
        mMapView.onCreate(savedInstanceState);

        if (aMap == null) {
            aMap = mMapView.getMap();
        }
        aMap.reloadMap();

        aMap.getUiSettings().setLogoPosition(1);
        aMap.getUiSettings().setScaleControlsEnabled(true);
        aMap.getUiSettings().setCompassEnabled(false);
        aMap.getUiSettings().setZoomControlsEnabled(false);
        aMap.getUiSettings().setTiltGesturesEnabled(false);
        aMap.getUiSettings().setRotateGesturesEnabled(false);
        setListener();

        converter = new CoordinateConverter(context);
        // CoordType.GPS 待转换坐标类型
        converter.from(CoordinateConverter.CoordType.GPS);

        onMapTypeChanged();
        aMap.moveCamera(CameraUpdateFactory.zoomTo(17));//for test
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (listener != null) {
                    listener.onInitComplete();
                }
            }
        }, 200);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        boolean flag = false;
        if (ev.getAction() == MotionEvent.ACTION_MOVE) {
//            if (!AGeoFencePresenter.isNull()) {
//                if (AGeoFencePresenter.getInstance().getShapeInstance().isGeofenceWillCross(ev.getX(), ev.getY())) {
//                    flag = true;
//                }
//            }
//            if (ev.getPointerCount() > 1) {
//                if (GlobalParams.hasPutGeofence && GlobalParams.addingFence) {
//                    float curDis = (float) Math.sqrt((ev.getX(0) - ev.getX(1)) * (ev.getX(0) - ev.getX(1)) + (ev.getY(0) - ev.getY(1)) * (ev.getY(0) - ev.getY(1)));
//                    float lastDis = (float) Math.sqrt((lastX0 - lastX1) * (lastX0 - lastX1) + (lastY0 - lastY1) * (lastY0 - lastY1));
//                    if (curDis < lastDis) {
//                        if (aMap.getUiSettings().isZoomGesturesEnabled()) {
//                            LatLng top = aMap.getProjection().fromScreenLocation(new Point(0, 0));
//                            LatLng bottom = aMap.getProjection().fromScreenLocation(new Point(0, DroneApplication.getInstance().getHeightPixels()));
//                            float screenHeightDistance = AMapUtils.calculateLineDistance(top, bottom);
//                            if (screenHeightDistance >= BaseGeoFenceShape.MAX_SIGHT_RADIUS * 3) {
//                                flag |= true;
//                            }
//                        }
//
//                    }
//                    lastX0 = ev.getX(0);
//                    lastY0 = ev.getY(0);
//                    lastX1 = ev.getX(1);
//                    lastY1 = ev.getY(1);
//                }
//            }
        }
        try {
            return flag || super.dispatchTouchEvent(ev);
        } catch (Exception e) {
//            e.printStackTrace();
        }
        return flag;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent motionEvent) {
        boolean intercept = false;
//        Fragment fragment = mFragmentManager.findFragmentById(R.id.pointsFragment);
//        if (fragment != null) {
//            intercept = PreventMistakenlyTouchHelper.onInterceptTouchEvent(motionEvent, fragment.getView());
//        }
//        fragment = mFragmentManager.findFragmentById(R.id.leftMenuFragment);
//        if (fragment != null) {
//            intercept |= PreventMistakenlyTouchHelper.onInterceptTouchEvent(motionEvent, fragment.getView());
//        }
//        fragment = mFragmentManager.findFragmentByTag(WayPointGlobalSettingFragment.class.getName());
//        if (fragment != null) {
//            View view = fragment.getView();
//            if (view != null) {
//                intercept |= PreventMistakenlyTouchHelper.onInterceptTouchEvent(motionEvent, view);
//            }
//        }
//        fragment = mFragmentManager.findFragmentByTag(WayPointSettingFragment.class.getName());
//        if (fragment != null) {
//            View view = fragment.getView();
//            if (view != null) {
//                intercept |= PreventMistakenlyTouchHelper.onInterceptTouchEvent(motionEvent, view);
//            }
//        }
//        fragment = mFragmentManager.findFragmentByTag(InterestPointSettingFragment.class.getName());
//        if (fragment != null) {
//            View view = fragment.getView();
//            if (view != null) {
//                intercept |= PreventMistakenlyTouchHelper.onInterceptTouchEvent(motionEvent, view);
//            }
//        }
//        fragment = mFragmentManager.findFragmentByTag(GeoFenceZoomFragment.class.getName());
//        if (fragment != null) {
//            View view = fragment.getView();
//            if (view != null) {
//                intercept |= PreventMistakenlyTouchHelper.onInterceptTouchEvent(motionEvent, view.findViewById(R.id.geofence_zoom_fragment_seekBar_container));
//            }
//        }
        return intercept | super.onInterceptTouchEvent(motionEvent);
    }

    private void setListener() {
//        drawerView.setOnDrawFinishListener(new DrawerView.OnDrawFinishListener() {
//            @Override
//            public void onDrawFinish(List<android.graphics.Point> points) {
//                points = MathUtils.simplifyPoints(points);
//                int left = GlobalParams.waypoints.size() < 100 ? 100 - GlobalParams.waypoints.size() : 0;
//                int count = points.size() < left ? points.size() : left;
//                for (int i = 0; i < count; i++) {
//                    android.graphics.Point point = points.get(i);
//                    LatLng latLng = aMap.getProjection().fromScreenLocation(point);
//                    LocationConverter.LatLng gcj02LatLng = LocationConverter.gcj02ToWgs84(new LocationConverter.LatLng(latLng.latitude, latLng.longitude));
//                    Waypoint wayPoint = new Waypoint(gcj02LatLng.latitude, gcj02LatLng.longitude);
//                    GlobalParams.waypoints.add(wayPoint);
////                    int index = GlobalParams.waypoints.size() + 1;
////                    addPointMarker(new LatLng(latLng.latitude, latLng.longitude), index, true);
////                    EventBusFactory.getUiBus().post(new AddOnePointEvent(index));
//                    InterestPointUtils.setWaypointInterestPointIndex(wayPoint);
//                }
//                EventBusFactory.getUiBus().post(new LoadPointsEvent(GlobalParams.waypoints));
//                EventBusFactory.getUiBus().post(new AddPointsFinishEvent());
//            }
//        });
//        aMap.setOnMapLongClickListener(new AMap.OnMapLongClickListener() {
//            @Override
//            public void onMapLongClick(LatLng latLng) {
//                if (GlobalParams.addingPoint && GlobalParams.getMissionStaus() != GlobalParams.MissionStatus.WAYPOINT_RUNNING) {
//                    mapFragment.showLongClickMenu(drawerView.touchX, drawerView.touchY, latLng.latitude, latLng.longitude);
//                    addLongClickMarker(latLng);
//                }
//            }
//        });
//        aMap.setOnMapClickListener(new AMap.OnMapClickListener() {
//            @Override
//            public void onMapClick(final LatLng latLng) {
//                if (InterestPointSettingFragment.isShow() || WayPointGlobalSettingFragment.isShow() || WayPointSettingFragment.isShow()) {
//                    EventBusFactory.getUiBus().post(new FragmentEvent("", 0));
//                    EventBusFactory.getUiBus().post(new CancelSelectPoint());
//                    return;
//                }
//                if (GlobalParams.addingFence) {
//                    AGeoFencePresenter.getInstance().getShapeInstance().setMap(aMap);
//                    AGeoFencePresenter.getInstance().putGeofence(latLng);
//                    return;
//                }
//                if (longClickMarker != null) {
//                    longClickMarker.remove();
//                    longClickMarker = null;
//                    mapFragment.hideLongClickMenu();
//                }
//                if (GlobalParams.addingInterest && GlobalParams.getMissionStaus() == GlobalParams.MissionStatus.NONE) {
//                    LocationConverter.LatLng gcj02LatLng = LocationConverter.gcj02ToWgs84(new LocationConverter.LatLng(latLng.latitude, latLng.longitude));
//                    int index = InterestPointUtils.addInterestPoint(gcj02LatLng.latitude, gcj02LatLng.longitude);
//                    addInterestMarker(latLng, index);
//                    EventBusFactory.getUiBus().post(new AddInterestPointFinishEvent());
//                    return;
//                }
//                if (GlobalParams.addingPoint
//                        && GlobalParams.getMissionStaus() != GlobalParams.MissionStatus.WAYPOINT_RUNNING
//                        && GlobalParams.getMissionStaus() != GlobalParams.MissionStatus.WAYPOINT_PAUSE
//                        && GlobalParams.waypoints.size() < 100) {
//                    int index = GlobalParams.waypoints.size() + 1;
//                    LocationConverter.LatLng gcj02LatLng = LocationConverter.gcj02ToWgs84(new LocationConverter.LatLng(latLng.latitude, latLng.longitude));
//                    Waypoint wayPoint = new Waypoint(gcj02LatLng.latitude, gcj02LatLng.longitude);
//                    GlobalParams.waypoints.add(wayPoint);
//                    EventBusFactory.getUiBus().post(new AddOnePointEvent(index));
//                    addPointMarker(latLng, index, true);
//                    InterestPointUtils.setWaypointInterestPointIndex(wayPoint);
//                    return;
//                }
//                if (GlobalParams.selectingLandPoint && GlobalParams.getMissionStaus() == GlobalParams.MissionStatus.NONE) {
//                    addLandPointMarker(latLng);
//                    GlobalParams.landLatLng= LocationConverter.gcj02ToWgs84(new LocationConverter.LatLng(latLng.latitude, latLng.longitude));
//                }
//            }
//        });
//        aMap.setOnMarkerClickListener(new AMap.OnMarkerClickListener() {
//            @Override
//            public boolean onMarkerClick(Marker marker) {
//                if (droneMarker != null && marker.getId().equals(droneMarker.getId())
//                        || controllerMarker != null && marker.getId().equals(controllerMarker.getId())) {
//                    return true;
//                }
//                if (GlobalParams.addingFence) {
//                    AGeoFencePresenter.getInstance().getShapeInstance().onMarkerClick(marker);
//                    return true;
//                }
//                if (pointMarkers.contains(marker)) {
//                    GlobalParams.sCurrentWayPointUserIndex = pointIds.get(marker.getId());
//                }
//                if (GlobalParams.addingPoint
//                        && GlobalParams.getMissionStaus() != GlobalParams.MissionStatus.WAYPOINT_RUNNING
//                        && GlobalParams.getMissionStaus() != GlobalParams.MissionStatus.WAYPOINT_PAUSE) {
//                    if (pointIds.containsKey(marker.getId())) {
//                        EventBusFactory.getUiBus().post(new PointMarkerClickEvent(pointIds.get(marker.getId())));
//                    } else if (interestIds.containsKey(marker.getId())) {
//                        GlobalParams.sCurrentPOIArrayIndex = interestMarkers.indexOf(marker);
//                        EventBusFactory.getUiBus().post(new FragmentEvent(InterestPointSettingFragment.class.getName(), FragmentEvent.EVENT_ADD_SHOW_REMOVE_UPDATE_FRAGMENT));
//                    }
//                }
////                else if(!GlobalParams.addingPoint&&!GlobalParams.addingFence&&pointIds.containsKey(marker.getId())&&GlobalParams.getMissionStaus()!= GlobalParams.MissionStatus.WAYPOINT_RUNNING){
////                    EventBusFactory.getUiBus().post(new StartFromIndexConfirmEvent(pointIds.get(marker.getId())));
////                }
//                return true;
//            }
//        });
//        aMap.setOnMarkerDragListener(new AMap.OnMarkerDragListener() {
//            @Override
//            public void onMarkerDragStart(Marker marker) {
//                if (GlobalParams.addingFence) {
//                    AGeoFencePresenter.getInstance().getShapeInstance().onMarkerDragStart(marker);
//                    return;
//                }
//            }
//
//            @Override
//            public void onMarkerDrag(Marker marker) {
//                if (GlobalParams.addingFence) {
//                    AGeoFencePresenter.getInstance().getShapeInstance().onMarkerDrag(marker);
//                    return;
//                }
//
//            }
//
//            @Override
//            public void onMarkerDragEnd(Marker marker) {
////                if(landPointMarker!=null&&marker.getId().equals(landPointMarker.getId())){
////                    GlobalParams.landLatLng= LocationConverter.gcj02ToWgs84(new LocationConverter.LatLng(marker.getPosition().latitude, marker.getPosition().longitude));
////                    return;
////                }
////                if (GlobalParams.addingFence) {
////                    AGeoFencePresenter.getInstance().getShapeInstance().onMarkerDragEnd(marker);
////                    return;
////                }
////
////                if (GlobalParams.addingPoint
////                        && GlobalParams.getMissionStaus() != GlobalParams.MissionStatus.WAYPOINT_RUNNING
////                        && GlobalParams.getMissionStaus() != GlobalParams.MissionStatus.WAYPOINT_PAUSE) {
////                    if (interestIds.containsKey(marker.getId())) {
////                        int index = interestIds.get(marker.getId());
////                        LocationConverter.LatLng gcj02LatLng = LocationConverter.gcj02ToWgs84(new LocationConverter.LatLng(marker.getPosition().latitude, marker.getPosition().longitude));
////                        for (InterestPoint interestPoint : GlobalParams.interestPoints) {
////                            if (interestPoint.index == index) {
////                                interestPoint.latitude = gcj02LatLng.latitude;
////                                interestPoint.longitude = gcj02LatLng.longitude;
////                                InterestPointUtils.moveInterestPoint(interestPoint);
////                            }
////                        }
////                        return;
////                    } else if (pointIds.containsKey(marker.getId())) {
////                        int index = pointIds.get(marker.getId());
////                        if (index <= GlobalParams.waypoints.size()) {
////                            LocationConverter.LatLng gcj02LatLng = LocationConverter.gcj02ToWgs84(new LocationConverter.LatLng(marker.getPosition().latitude, marker.getPosition().longitude));
////                            GlobalParams.waypoints.get(index - 1).setLatitude(gcj02LatLng.latitude);
////                            GlobalParams.waypoints.get(index - 1).setLongitude(gcj02LatLng.longitude);
////                        }
////                        if (GlobalParams.route.getRouteType() == MapConfigRequest.AIRLINE_TYPE_STRAIGHT) {
////                            drawRoute(unFlyedRouteColor, routeWidth);
////                        } else {
////                            drawCurveRoute(unFlyedRouteColor, routeWidth, GlobalParams.waypoints.size());
////                        }
////                    }
////                }
//            }
//        });
//
//        aMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
//            private float minZoom;
//            private float startZoom=0;
//            private float lastScale;
//
//            @Override
//            public void onCameraChange(CameraPosition cameraPosition) {
//                if(GlobalParams.addingFence&&cameraPosition.zoom<FENCE_MAX_MAP_ZOOM){
//                    aMap.moveCamera(CameraUpdateFactory.zoomTo(FENCE_MAX_MAP_ZOOM));
//                }
//                if(lastScale==0){
//                    lastScale=aMap.getScalePerPixel();
//                }
//                if(GlobalParams.addingFence&&!AGeoFencePresenter.isNull()&&cameraPosition.zoom!=startZoom){
//                    double minPxDis = AGeoFencePresenter.getInstance().getShapeInstance().getMinPxDis();
//                    if(minPxDis> MIN_PX){
//                        minZoom=cameraPosition.zoom;
//                    }
//                    LogUtils.e("minPxDis = "+minPxDis +"   minZoom = "+minZoom);
//                    if(minPxDis>0&&minPxDis< MIN_PX &&minZoom!=0){
//                        aMap.moveCamera(CameraUpdateFactory.zoomTo(minZoom));
//                    }
//                }
//                if(startZoom==0){
//                    startZoom=cameraPosition.zoom;
//                }
//                if(minZoom==0){
//                    minZoom=cameraPosition.zoom;
//                }
//            }
//
//            @Override
//            public void onCameraChangeFinish(CameraPosition cameraPosition) {
//                if(!AGeoFencePresenter.isNull()&&cameraPosition.zoom!=startZoom){
//                    double minPxDis = AGeoFencePresenter.getInstance().getShapeInstance().getMinPxDis();
//                    if(minPxDis> MIN_PX){
//                        float scale = lastScale / aMap.getScalePerPixel();
//                        lastScale = aMap.getScalePerPixel();
//                        if (BaseGeoFenceShape.cameraChangeByBoundVisible) {
//                            BaseGeoFenceShape.cameraChangeByBoundVisible = false;
//                            return;
//                        }
//                        if (GeoFenceZoomFragment.isShow() && GlobalParams.hasPutGeofence) {
//                            EventBusFactory.getUiBus().post(new FragmentEvent(GeoFenceZoomFragment.class.getName(), FragmentEvent.EVENT_UPDATE, scale));
//                        }
//                    }
//                }else {
//                    minZoom=cameraPosition.zoom;
//                }
//                startZoom=cameraPosition.zoom;
//            }
//        });
    }

    @Override
    protected void onMapTypeChanged() {
        switch (mapType) {
            case NORMAL:
                aMap.setMapType(AMap.MAP_TYPE_NORMAL);
                break;
            case SATELLITE:
                aMap.setMapType(AMap.MAP_TYPE_SATELLITE);
                break;
            case NIGHT:
                aMap.setMapType(AMap.MAP_TYPE_NIGHT);
                break;
        }
    }

    @Override
    public void onPointDelete(int index) {
//        Marker marker = pointMarkers.get(index - 1);
//        if (circles.containsKey(marker.getId())) {
//            circles.get(marker.getId()).remove();
//            circles.remove(marker.getId());
//        }
//        pointIds.remove(marker.getId());
//        marker.remove();
//        pointMarkers.remove(index - 1);
//        for (int i = index - 1; i < pointMarkers.size(); i++) {
//            pointMarkers.get(i).setIcon(getPointMarkerIcon(i + 1, true, GlobalParams.waypoints.get(i).getYaw()));
//            pointIds.put(pointMarkers.get(i).getId(), i + 1);
//        }
//        if (GlobalParams.route.getRouteType() == MapConfigRequest.AIRLINE_TYPE_STRAIGHT) {
//            drawRoute(unFlyedRouteColor, routeWidth);
//        } else {
//            drawCurveRoute(unFlyedRouteColor, routeWidth, GlobalParams.waypoints.size());
//        }
    }

    @Override
    public void removeLongClickMarker() {
        if (longClickMarker != null) {
            longClickMarker.remove();
            longClickMarker = null;
        }
    }

    @Override
    public void removeLandPointMarker() {
        if (landPointMarker != null) {
            landPointMarker.remove();
            landPointMarker = null;
        }
    }

    @Override
    public void insertOnePoint(int index, double latitude, double longitude) {
//        LocationConverter.LatLng gcj02LatLng = LocationConverter.gcj02ToWgs84(new LocationConverter.LatLng(latitude, longitude));
//        GlobalParams.waypoints.add(index - 1, new Waypoint(gcj02LatLng.latitude, gcj02LatLng.longitude));
//        insertPointMarker(new LatLng(latitude, longitude), index);
//        for (int i = index; i < pointMarkers.size(); i++) {
//            pointMarkers.get(i).setIcon(getPointMarkerIcon(i + 1, true, 0));
//            pointIds.put(pointMarkers.get(i).getId(), i + 1);
//        }
//        if (GlobalParams.route.getRouteType() == MapConfigRequest.AIRLINE_TYPE_STRAIGHT) {
//            drawRoute(unFlyedRouteColor, routeWidth);
//        } else {
//            drawCurveRoute(unFlyedRouteColor, routeWidth, GlobalParams.waypoints.size());
//        }
    }

    @Override
    public void addPointCircle(int index, int radius) {
        if (index > pointMarkers.size()) {
            return;
        }
        Marker marker = pointMarkers.get(index - 1);
        if (circles.containsKey(marker.getId())) {
            if (radius == 0) {
                circles.get(marker.getId()).remove();
                circles.remove(marker.getId());
            } else {
                circles.get(marker.getId()).setRadius(radius);
            }
        } else if (radius > 0) {
            CircleOptions circleOptions = new CircleOptions();
            circleOptions.center(marker.getPosition());
            circleOptions.radius(radius);
            circleOptions.strokeColor(cirlceStrokeColor);
            circleOptions.fillColor(cirlceFillColor);
            circleOptions.strokeWidth(cirlceWidth);
            circleOptions.zIndex(998);
            Circle circle = aMap.addCircle(circleOptions);
            circles.put(pointMarkers.get(index - 1).getId(), circle);
        }
    }

    @Override
    public void changeMarkerRotateAngle(int index, float targetAngle) {
        if (index >= 0 && index <= pointMarkers.size()) {
            pointMarkers.get(index - 1).setIcon(getPointMarkerIcon(index, true, targetAngle));
        }
    }

    @Override
    public void drawDroneMarker(double latitude, double longitude, float angle) {
        droneLocation = getConvertedLatLng(latitude, longitude);
        droneAngle = angle;
        drawDroneMarker();
        setPanAngle(panAngle);
    }

    @Override
    public void setPanAngle(int angle) {
        panAngle = angle;
        if (droneLocation == null) {
            return;
        }
        if (GlobalParams.cameraType != null) {
            if (panMarker == null || !panMarker.isVisible()) {
                MarkerOptions markerOptions = new MarkerOptions();
                markerOptions.position(droneLocation);
                markerOptions.draggable(true);
                markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_camera_direction));// 设置图标
                markerOptions.anchor(0.5f, 0.5f);
                markerOptions.zIndex(1001);
                markerOptions.draggable(false);
                panMarker = aMap.addMarker(markerOptions);
                panMarker.setRotateAngle(360 - panAngle);
            } else {
                panMarker.setPosition(droneLocation);
                panMarker.setRotateAngle(360 - panAngle);
            }
        } else if (panMarker != null) {
            panMarker.remove();
            panMarker.destroy();
            panMarker = null;
        }
    }

    private void drawDroneMarker() {
        if (droneMarker == null || !droneMarker.isVisible()) {
            MarkerOptions markerOptions = new MarkerOptions();
            markerOptions.position(droneLocation);
            markerOptions.draggable(true);
            markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_drone_direction));// 设置图标
            markerOptions.anchor(0.5f, 0.5f);
            markerOptions.zIndex(1002);
            markerOptions.draggable(false);
            droneMarker = aMap.addMarker(markerOptions);
            droneMarker.setRotateAngle(360 - droneAngle);
        } else {
            droneMarker.setPosition(droneLocation);
            droneMarker.setRotateAngle(360 - droneAngle);
        }
        checkMoveCamera();
    }

    @Override
    public void drawControllerMarker(double latitude, double longitude) {
        controllerLocation = getConvertedLatLng(latitude, longitude);
        drawControllerMarker();
    }

    private void drawControllerMarker() {
        if (controllerMarker == null || !controllerMarker.isVisible()) {
            MarkerOptions markerOptions = new MarkerOptions();
            markerOptions.position(controllerLocation);
            markerOptions.draggable(true);
            markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_controller_marker));// 设置图标
            markerOptions.anchor(0.5f, 0.5f);
            markerOptions.zIndex(1000);
            markerOptions.draggable(false);
            controllerMarker = aMap.addMarker(markerOptions);
            if (droneLocation == null) {
                aMap.moveCamera(CameraUpdateFactory.changeLatLng(controllerLocation));
            }
        } else {
            controllerMarker.setPosition(controllerLocation);
        }
    }

    @Override
    public void exitPointType() {
        clearPoints();
        clearInterestPoints();
    }

    private void clearPoints() {
        for (Marker marker : pointMarkers) {
            marker.remove();
            marker.destroy();
        }
        pointMarkers.clear();
        pointIds.clear();
        if (unFliedRoute != null) {
            unFliedRoute.remove();
            unFliedRoute = null;
        }
        if (fliedRoute != null) {
            fliedRoute.remove();
            fliedRoute = null;
        }
        for (String key : circles.keySet()) {
            circles.get(key).remove();
        }
        circles.clear();
        if (longClickMarker != null) {
            longClickMarker.remove();
            longClickMarker = null;
            mapFragment.hideLongClickMenu();
        }
        if (landPointMarker != null) {
            landPointMarker.remove();
            landPointMarker = null;
        }
    }

    private void clearInterestPoints() {
        for (Marker marker : interestMarkers) {
            marker.remove();
            marker.destroy();
        }
        interestMarkers.clear();
        interestIds.clear();
    }

    @Override
    public void moveCameraToDroneLocation() {
        if (droneLocation != null) {
            aMap.moveCamera(CameraUpdateFactory.changeLatLng(droneLocation));
        }
    }

    @Override
    public void moveCameraToControllerLocation() {
        if (controllerLocation != null) {
            aMap.moveCamera(CameraUpdateFactory.changeLatLng(controllerLocation));
        }
    }

    @Override
    public void checkMoveCamera() {
        if (!GlobalParams.droneFlying) {
            return;
        }
        if (GlobalParams.videoViewStatus == GlobalParams.ViewStatus.MAX) {
            aMap.moveCamera(CameraUpdateFactory.changeLatLng(droneLocation));
        } else {
            android.graphics.Point point = aMap.getProjection().toScreenLocation(droneLocation);
            if (point.x < droneMinScreenX || point.x > droneMaxScreenX || point.y < droneMinScreenY || point.y > droneMaxScreenY) {
                aMap.moveCamera(CameraUpdateFactory.changeLatLng(droneLocation));
            }
        }
    }

    public ArrayList<LatLng> getCurveRouteLatlngs(int startIndex, int endIndex) {//index start from 1
        ArrayList<LatLng> latlngs = new ArrayList<>();
        ArrayList<Vector2> vector2s = getCurveRouteVector2s(startIndex, endIndex);
        for (Vector2 vector2 : vector2s) {
            latlngs.add(getConvertedLatLng(vector2.x, vector2.y));
        }
        return latlngs;
    }

    @Override
    public void setCurrentWaypointIndex(int index) {
//        int max = index < pointMarkers.size() ? index : pointMarkers.size();
//        Marker tmp;
//        ArrayList<LatLng> latlngs = new ArrayList<>();
//        if (fliedRoute != null) {
//            fliedRoute.remove();
//        }
//        for (int i = 0; i < max; i++) {
//            tmp = pointMarkers.get(i);
//            tmp.setIcon(getPointMarkerIcon(i + 1, false, GlobalParams.waypoints.get(i).getYaw()));
//            if (GlobalParams.route.getRouteType() == MapConfigRequest.AIRLINE_TYPE_STRAIGHT) {
//                latlngs.add(getConvertedLatLng(GlobalParams.waypoints.get(i).latitude, GlobalParams.waypoints.get(i).longitude));
//            }
//        }
//        if (GlobalParams.route.getRouteType() == MapConfigRequest.AIRLINE_TYPE_CURVE) {
//            latlngs = getCurveRouteLatlngs(1, max);
//        }
//        fliedRoute = drawRoute(latlngs, flyedRouteColor, routeWidth);
//        latlngs.clear();
//        if (unFliedRoute != null) {
//            unFliedRoute.remove();
//        }
//        if (GlobalParams.route.getRouteType() == MapConfigRequest.AIRLINE_TYPE_STRAIGHT) {
//            if (max > 0) {
//                latlngs.add(getConvertedLatLng(GlobalParams.waypoints.get(max - 1).latitude, GlobalParams.waypoints.get(max - 1).longitude));
//            }
//            for (int i = max; i < pointMarkers.size(); i++) {
//                tmp = pointMarkers.get(i);
//                tmp.setIcon(getPointMarkerIcon(i + 1, true, GlobalParams.waypoints.get(i).getYaw()));
//                latlngs.add(getConvertedLatLng(GlobalParams.waypoints.get(i).latitude, GlobalParams.waypoints.get(i).longitude));
//            }
//        } else {
//            latlngs = getCurveRouteLatlngs(max, pointMarkers.size());
//            for (int i = max; i < pointMarkers.size(); i++) {
//                tmp = pointMarkers.get(i);
//                tmp.setIcon(getPointMarkerIcon(i + 1, true, GlobalParams.waypoints.get(i).getYaw()));
//            }
//        }
//        unFliedRoute = drawRoute(latlngs, unFlyedRouteColor, routeWidth);
    }

//    @Override
//    public void loadPoints(ArrayList<Waypoint> waypoints) {
//        clearPoints();
//        addPointMarkers(waypoints);
//    }
//
//    @Override
//    public void loadInterestPoints(ArrayList<InterestPoint> interestPoints) {
//        clearInterestPoints();
//        addInterestMarkers(interestPoints);
//    }

    @Override
    public void changeRouteType(byte routeType) {
//        ArrayList<LatLng> latlngs = new ArrayList<>();
//        if (unFliedRoute != null) {
//            unFliedRoute.remove();
//        }
//        if (routeType == MapConfigRequest.AIRLINE_TYPE_STRAIGHT) {
//            for (Waypoint waypoint : GlobalParams.waypoints) {
//                latlngs.add(getConvertedLatLng(waypoint.latitude, waypoint.longitude));
//            }
//        } else {
//            latlngs = getCurveRouteLatlngs(1, pointMarkers.size());
//        }
//        unFliedRoute = drawRoute(latlngs, unFlyedRouteColor, routeWidth);
    }

//    private void addInterestMarkers(ArrayList<InterestPoint> interestPoints) {
//        for (int i = 0; i < interestPoints.size(); i++) {
//            MarkerOptions markerOptions = new MarkerOptions();
//            markerOptions.position(getConvertedLatLng(interestPoints.get(i).latitude, interestPoints.get(i).longitude));
//            markerOptions.draggable(true);
//            markerOptions.icon(getInterestPointMarkerIcon(i + 1));
//            markerOptions.anchor(0.5f, 1f);
//            markerOptions.zIndex(999);
//            Marker marker = aMap.addMarker(markerOptions);
//            interestIds.put(marker.getId(), interestPoints.get(i).index);
//            interestMarkers.add(marker);
//        }
//    }

    @Override
    public void setPointMarkerDraggable(boolean draggable) {
        for (Marker marker : pointMarkers) {
            marker.setDraggable(draggable);
        }
    }

    @Override
    public void setLandPointMarkerDraggable(boolean draggable) {
        if (landPointMarker != null) {
            landPointMarker.setDraggable(draggable);
        }
    }

    @Override
    public void setFenceMarkerDraggable(boolean draggable) {
//        if(!AGeoFencePresenter.isNull()){
//            AGeoFencePresenter.getInstance().getShapeInstance().setMarkerDraggable(draggable);
//        }
    }

    public void addLongClickMarker(LatLng latLng) {
        if (longClickMarker != null) {
            longClickMarker.remove();
        }
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_insert_point));
        markerOptions.position(latLng);
        markerOptions.draggable(false);
        markerOptions.zIndex(999);
        markerOptions.anchor(0.5f, 0.5f);
        longClickMarker = aMap.addMarker(markerOptions);
    }

    public void addLandPointMarker(LatLng latLng) {
        if (landPointMarker != null) {
            landPointMarker.remove();
        }
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_land_point_marker));
        markerOptions.position(latLng);
        markerOptions.draggable(true);
        markerOptions.zIndex(999);
        markerOptions.anchor(0.5f, 0.5f);
        landPointMarker = aMap.addMarker(markerOptions);
    }

    public void addInterestMarker(LatLng latLng, int index) {
//        MarkerOptions markerOptions = new MarkerOptions();
//        markerOptions.icon(getInterestPointMarkerIcon(InterestPointUtils.getActualInterestIndex(index)));
//        markerOptions.position(latLng);
//        markerOptions.draggable(true);
//        markerOptions.zIndex(999);
//        markerOptions.anchor(0.5f, 1f);
//        Marker marker = aMap.addMarker(markerOptions);
//        interestMarkers.add(marker);
//        interestIds.put(marker.getId(), index);
    }

    @Override
    public void onInterestPointDelete(int index) {
        for (String key : interestIds.keySet()) {
            if (interestIds.get(key) == index) {
                interestIds.remove(key);
                for (Marker marker : interestMarkers) {
                    if (marker.getId().equals(key)) {
                        interestMarkers.remove(marker);
                        marker.remove();
                        marker.destroy();
                        break;
                    }
                }
                break;
            }
        }
        for (int i = 0; i < interestMarkers.size(); i++) {
            interestMarkers.get(i).setIcon(getInterestPointMarkerIcon(i + 1));
        }
    }

    public void insertPointMarker(LatLng latLng, int index) {
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latLng);
        markerOptions.draggable(true);
        markerOptions.icon(getPointMarkerIcon(index, true, 0));// 设置图标
        markerOptions.anchor(0.5f, 0.5f);
        markerOptions.zIndex(999);
        Marker marker = aMap.addMarker(markerOptions);
        pointIds.put(marker.getId(), index);
        pointMarkers.add(index - 1, marker);
    }

    public void addPointMarker(LatLng latLng, int index, boolean enable) {
//        MarkerOptions markerOptions = new MarkerOptions();
//        markerOptions.position(latLng);
//        markerOptions.draggable(true);
//        markerOptions.icon(getPointMarkerIcon(index, enable, 0));// 设置图标
//        markerOptions.anchor(0.5f, 0.5f);
//        markerOptions.zIndex(999);
//        Marker marker = aMap.addMarker(markerOptions);
//        pointIds.put(marker.getId(), index);
//        pointMarkers.add(index - 1, marker);
//        if (GlobalParams.route.getRouteType() == MapConfigRequest.AIRLINE_TYPE_STRAIGHT) {
//            drawRoute(unFlyedRouteColor, routeWidth);
//        } else {
//            drawCurveRoute(unFlyedRouteColor, routeWidth, index);
//        }
    }

    public void drawCurveRoute(int color, int width, int index) {
//        Polyline tmp = unFliedRoute;
//        if (GlobalParams.waypoints.size() == 0) {
//            unFliedRoute = null;
//        }
//        if (GlobalParams.waypoints.size() < 2) {
//            return;
//        }
//        unFliedRoute = drawRoute(getCurveRouteLatlngs(1, index), color, width);
//        if (tmp != null) {
//            tmp.remove();
//        }
    }

//    public void addPointMarkers(ArrayList<Waypoint> waypoints) {
//        for (int i = 0; i < waypoints.size(); i++) {
//            MarkerOptions markerOptions = new MarkerOptions();
//            markerOptions.position(getConvertedLatLng(waypoints.get(i).getLatitude(), waypoints.get(i).getLongitude()));
//            markerOptions.draggable(true);
//            Waypoint waypoint = waypoints.get(i);
//            int interestPointIndex = waypoint.getInterestPointIndex();
//            if (interestPointIndex != 0) {
//                markerOptions.icon(getPointMarkerIcon(i + 1, true, InterestPointUtils.getToIntersetPointYaw(waypoint, interestPointIndex)));
//            } else {
//                markerOptions.icon(getPointMarkerIcon(i + 1, true, waypoint.getYaw()));
//            }
//            markerOptions.anchor(0.5f, 0.5f);
//            markerOptions.zIndex(999);
//            Marker marker = aMap.addMarker(markerOptions);
//            pointIds.put(marker.getId(), i + 1);
//            pointMarkers.add(i, marker);
//        }
//        if (GlobalParams.route.getRouteType() == MapConfigRequest.AIRLINE_TYPE_STRAIGHT) {
//            drawRoute(unFlyedRouteColor, routeWidth);
//        } else {
//            drawCurveRoute(unFlyedRouteColor, routeWidth, waypoints.size());
//        }
//    }

    private BitmapDescriptor getPointMarkerIcon(int index, boolean enable, float angle) {
        TextView tv = new TextView(context);
        int length = context.getResources().getDimensionPixelOffset(R.dimen.point_marker_size);
        if (enable) {
            tv.setBackground(BitmapUtils.getBitmapDrawableWithAngle(context, R.drawable.bg_point_normal, length, angle));
        } else {
            tv.setBackground(BitmapUtils.getBitmapDrawableWithAngle(context, R.drawable.bg_point_disable, length, angle));
        }
        tv.setText("" + index);
        tv.setTextSize(20);
        tv.setTextColor(Color.WHITE);
        tv.setGravity(Gravity.CENTER);
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(length, length);
        tv.setLayoutParams(params);
        return BitmapDescriptorFactory.fromView(tv);
    }

    private BitmapDescriptor getInterestPointMarkerIcon(int index) {
        TextView tv = new TextView(context);
        int length = context.getResources().getDimensionPixelOffset(R.dimen.interest_point_marker_size);
        tv.setBackground(BitmapUtils.getBitmapDrawableWithAngle(context, R.drawable.ic_interest_marker, length, 0));
        tv.setText("" + index);
        tv.setTextSize(18);
        tv.setPadding(0, 5, 0, 0);
        tv.setTextColor(Color.WHITE);
        tv.getPaint().setFakeBoldText(true);
        tv.setGravity(Gravity.CENTER);
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(length, length);
        tv.setLayoutParams(params);
        return BitmapDescriptorFactory.fromView(tv);
    }

    public Polyline drawRoute(ArrayList<LatLng> latlngs, int color, int width) {
        PolylineOptions options = new PolylineOptions();
        options.width(width);
        options.color(color);
        options.addAll(latlngs);
        options.zIndex(997);
        return aMap.addPolyline(options);
    }

    public void drawRoute(int color, int width) {
//        Polyline tmp = unFliedRoute;
//        if (GlobalParams.waypoints.size() == 0) {
//            unFliedRoute = null;
//        }
//        ArrayList<LatLng> latlngs = new ArrayList<>();
//        for (Waypoint waypoint : GlobalParams.waypoints) {
//            latlngs.add(getConvertedLatLng(waypoint.latitude, waypoint.longitude));
//        }
//        unFliedRoute = drawRoute(latlngs, color, width);
//        if (tmp != null) {
//            tmp.remove();
//        }
    }

    @Override
    public void onPause() {
        mMapView.onPause();
    }

    @Override
    public void onResume() {
        mMapView.onResume();
    }

    @Override
    public void onDestroy() {
        aMap.clear();
        pointMarkers.clear();
        interestMarkers.clear();
        pointIds.clear();
        interestIds.clear();
        circles.clear();
        longClickMarker = null;
        droneMarker = null;
        panMarker = null;
        controllerMarker = null;
        droneLocation = null;
        controllerLocation = null;
        droneAngle = 0;
        panAngle = 0;
        unFliedRoute = null;
        fliedRoute = null;
        mMapView.onDestroy();
        mapFragment = null;
    }

    @Override
    public void clearMap() {
        if (fliedRoute != null) {
            fliedRoute.remove();
            fliedRoute = null;
        }
        aMap.clear();
        if (controllerLocation != null) {
            controllerMarker = null;
            drawControllerMarker();
        }
        if (droneLocation != null) {
            droneMarker = null;
            drawDroneMarker();
        }
    }

    @Override
    public void checkFenceMapZoom() {
        if (aMap.getCameraPosition().zoom < FENCE_MAX_MAP_ZOOM) {
            aMap.moveCamera(CameraUpdateFactory.zoomTo(FENCE_MAX_MAP_ZOOM));
        }
    }

    private LatLng getConvertedLatLng(double latitude, double longitude) {
        // sourceLatLng待转换坐标点
        converter.coord(new LatLng(latitude, longitude));
        return converter.convert();
    }

}
